<?php

$templates = $db->fetchAll("SELECT * FROM site_templates WHERE site_id=? ORDER BY sort", $site['id']);
$smarty->assign('templates', $templates);


if (isset($_REQUEST['id'])) {
	$template = $db->fetchRow("SELECT * FROM site_templates WHERE id=? AND site_id=?", array($_REQUEST['id'], $site['id']));
	$template['plugins'] = array_index($db->fetchAll("SELECT file, config FROM site_templates_plugins WHERE template_id=?", $template['id']), 'file');
	
	/*
	 * Find available plugins
	 *
	 */
	$all_plugins = array();
	foreach(glob($app_root . $site['home_dir'] . '/plugins/*') as $file) {
		if (is_dir($file) and file_exists($file .'/' . basename($file) . '.php')) {
			$file = $file .'/' . basename($file) . '.php';
		}
		if (preg_match('/\.php$/m', $file)) {
			$plugin = parse_plugin($file, $template['plugins']);
			if (isset($plugin['name'])) {
				$all_plugins[$plugin['file']] = $plugin;
			}
		}
	}
	foreach(glob($app_root . '/admin/plugins/*') as $file) {
		if (is_dir($file) and file_exists($file .'/' . basename($file) . '.php')) {
			$file = $file .'/' . basename($file) . '.php';
		}
		if (preg_match('/\.php$/', $file)) {
			$plugin = parse_plugin($file, $template['plugins']);
			if (isset($plugin['name'])) {
				$all_plugins[$plugin['file']] = $plugin;
			}
		}
	}
	uasort($all_plugins, create_function('$a,$b', 'return ($a["name"] < $b["name"]) ? -1 : 1;'));
	$template['plugins'] = $all_plugins;
	
	/*
	 * Find out how many pages use this template.
	 *
	 */
	$template['active_pages']  = count($db->fetchCol("SELECT p.id FROM site_pages p LEFT JOIN site_pages_revisions r ON p.revision_id=r.id WHERE template_id=?", $template['id']));
	$template['pending_pages'] = count($db->fetchCol("SELECT p.id FROM site_pages_revisions r JOIN site_pages p ON r.page_id=p.id WHERE r.id=(SELECT MAX(id) FROM site_pages_revisions WHERE page_id=r.page_id) AND template_id=? AND p.revision_id!=r.id;", $template['id']));
	
	/*
	 * If we've got post then save
	 *
	 */
	
	if (isset($_POST['template'])) {
		if (isset($_POST['template']['plugins'])) {
			foreach($_POST['template']['plugins'] as $file => $plugin) {
				$template['plugins'][$file] = array_merge($template['plugins'][$file], $_POST['template']['plugins'][$file]);
				if (!isset($_POST['template']['plugins'][$file]['enabled'])) unset($template['plugins'][$file]['enabled']);
			}
		}
		$template['title'] = $_POST['template']['title'];
		$template['file']  = $_POST['template']['file'];

		$errors = array();
		if (!$template['title']) $errors[] = 'TITLE';
		if (!$template['file'])  $errors[] = 'FILE';
		if (!file_exists("{$app_root}{$site['home_dir']}/templates/site/{$template['file']}"))  $errors[] = 'FILEEXIST';

		if (sizeof($errors)) {
			$smarty->assign('errors', $errors);
		} else {
			$smarty->assign('success', true);
			$db->beginTransaction();
			try {
				$db->delete('site_templates_plugins', $db->quoteInto("template_id=?", $site['id']));
				foreach($template['plugins'] as $plugin) {
					if (isset($plugin['enabled']) and $plugin['enabled']) {
						$db->insert('site_templates_plugins', array(
							'template_id' => $template['id'],
							'file'        => $plugin['file'],
							'config'      => $plugin['config']
						));
					}
				}
			} catch (Exception $e) {
				$db->rollback();
				$logger->warn($e->getMessage());
			}
			$db->update('site_templates', array(
				'title' => $template['title'],
				'file'  => $template['file']
			), $db->quoteInto('id=?', $template['id']));
		}
	}
	
	
	
	$smarty->assign('template', $template);
	
	
}



if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
	header('Content-type: text/xml');
	$smarty->display('site/templates/index.tpl.taconite');
} else {
	$smarty->display('site/templates/index.tpl.html');
}
